package com.zsummer.baikal.system.controller;


import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsummer.baikal.common.web.R;
import com.zsummer.baikal.system.dto.SysUserDTO;
import com.zsummer.baikal.system.entity.SysUser;
import com.zsummer.baikal.system.service.ISysUserService;
import com.zsummer.baikal.system.vo.SysUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * 用户表 前端控制器
 *
 * @author zsummer
 * @since 2021-07-28
 */
@Api(value = "用户管理", tags = "用户管理")
@RestController
@RequestMapping("/system/users")
@RequiredArgsConstructor
public class SysUserController {

    private final ISysUserService sysUserService;

    private final PasswordEncoder passwordEncoder;

//    @GetMapping
//    @PreAuthorize("hasAuthority('sys_menu_add')")
//    public Object list() {
//        List<SysUser> users = sysUserService.list();
//        return R.ok(users);
//    }

//    @ApiOperation(value = "用户列表")
//    @GetMapping
//    public R<IPage<List<SysUser>>> searchUser(Page page, SysUserSearchDTO searchDTO) {
//        return R.ok(sysUserService.page(page, new QueryWrapper<SysUser>()
//                .lambda()
//                .eq(searchDTO != null && StrUtil.isNotBlank(searchDTO.getUsername()), SysUser::getUsername, searchDTO.getUsername())
//                .eq(searchDTO != null && searchDTO.getDeptId() != null, SysUser::getDeptId, searchDTO.getDeptId())));
//    }

    @ApiOperation(value = "用户列表")
    @GetMapping
    public R<IPage<SysUserVO>> searchUser(Page page, SysUserDTO searchDTO) {
        return R.ok(sysUserService.searchUser(page, searchDTO));
    }

    @ApiOperation(value = "用户详情")
    @GetMapping("/{id}")
    public R<SysUser> getUser(@PathVariable("id") Long id) {
        return R.ok(sysUserService.getUserVoById(id));
    }

    @ApiOperation(value = "添加用户")
    @PostMapping
    public R addUser(@Validated @RequestBody SysUser sysUser) {
        SysUser selectedUse = sysUserService.getOne(new QueryWrapper<SysUser>()
                .lambda()
                .eq(SysUser::getUsername, sysUser.getUsername()));
        if (selectedUse != null) {
            throw new IllegalArgumentException("用户名已存在");
        }
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        sysUser.setCreateTime(LocalDateTime.now());
        sysUser.setDelFlag("0");
        sysUser.setLockFlag("0");
        if(sysUserService.save(sysUser)) {
            return R.ok();
        }
        return R.failed();
    }

    @ApiOperation(value = "更新用户")
    @PutMapping
    public R updateUser(@RequestBody SysUser sysUser) {
        Assert.notNull(sysUser.getUserId(), "用户ID不能为空");
        SysUser selectedUser = sysUserService.getById(sysUser.getUserId());
        Assert.notNull(selectedUser, "更新用户不存在");
        if (!selectedUser.getUsername().equals(sysUser.getUsername())) {
            throw new IllegalArgumentException("用户名不能修改");
        }
        sysUser.setUpdateTime(LocalDateTime.now());
        if (StrUtil.isNotBlank(sysUser.getPassword())){
            sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));
        }
        if (sysUserService.updateById(sysUser)) {
            return R.ok();
        }
        return R.failed("修改失败");
    }

    @ApiOperation("删除用户")
    @DeleteMapping("/{userIds}")
    public R deleteUsers(@PathVariable Long[] userIds) {
        if (sysUserService.removeByIds(Arrays.asList(userIds))) {
            return R.ok();
        }
        return R.failed("删除失败");
    }
}
